package com.neobeai.algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xp
 * @date 2024/12/9 16:03
 * @description
 */
public class Demo1 {

    public static void main(String[] args) {
        String s = "abcdfebgcbbe";
//        System.out.println(s.charAt(1));
//        String result = getMaxLongChildStr(s);
//        System.out.println(result);
        int maxLength = lengthOfLongestSubstring(s);
        System.out.println(maxLength);
    }

    /**
     * 求最长连续递增子串
     * @param s
     * @return
     */
    private static String getMaxLongChildStr(String s) {
        int curLength = 0, maxLength = 0;
        int i = 0, j = 1;
        int maxStartIndex = 0;
        while (j < s.length()) {
            if (s.charAt(j) - s.charAt(i) == (curLength + 1)) {
                curLength++;
                j++;
                if (curLength > maxLength) {
                    maxLength = curLength;
                    maxStartIndex = i;
                }
                continue;
            }
            if (curLength > maxLength) {
                maxLength = curLength;
                maxStartIndex = i;
            }
            curLength = 0;
            i = j;
            j++;
        }
        int endIndex = maxStartIndex + maxLength;
        System.out.println("开始索引: " + maxStartIndex + ", 结束索引: " + endIndex);
        return s.substring(maxStartIndex, endIndex + 1);
    }

    /**
     * 获取最长非重复子串的长度
     * 输入：s = "abcabcbb"
     * 输出：3
     * @param s
     * @return
     */
    public static int lengthOfLongestSubstring(String s) {
        // abcabcbb
        int left = 0;
        int maxLength = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int right = 0; right < s.length(); right ++) {
            char c = s.charAt(right);
            if (map.containsKey(c) && left <= map.get(c)) {
                left = map.get(c) + 1;
            }
            map.put(c, right);
            maxLength = Math.max(maxLength, right - left + 1);
        }
        return maxLength;
    }

}
